package com.java.netty.server.pptp;

import com.alibaba.fastjson.JSON;
import com.java.netty.common.codec.Packet;
import com.java.netty.common.pptp.EnvQuest;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    public ServerHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + "上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println(channel.remoteAddress() + "下线");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //解析java-netty-client 发过来的包
        Packet packet = JSON.toJavaObject((JSON) JSON.toJSON(msg), Packet.class);
        //获取命令号
        int cmd = packet.cmd;
        //这里只模拟一种命令号  发env
        EnvQuest envQuest = JSON.parseObject(packet.data, EnvQuest.class);
        System.out.println("命令号:" + packet.getCmd());
        System.out.println("协议版本:" + packet.getProtocolVer());
        System.out.println("待命时间:" + packet.getOnCallTime());
        System.out.println("actId:" + envQuest.getExt().getActiveId());
        System.out.println("channelRead");
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
    }
}
